import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_taotaoshipin/app/app_controller.dart';
import 'package:flutter_taotaoshipin/http/dao/interact_dao.dart';
import 'package:get/get.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';

import 'feedback_state.dart';

class FeedbackController extends GetxController {
  final FeedbackState state = FeedbackState();

  final TextEditingController feedbackEditingController =
      TextEditingController();
  final TextEditingController phoneEditingController = TextEditingController();

  @override
  void onInit() {
    super.onInit();
  }

  @override
  void onReady() {
    super.onReady();
    feedbackEditingController.addListener(() {
      update();
    });
    phoneEditingController.addListener(() {
      update();
    });
  }

  @override
  void onClose() {
    feedbackEditingController.dispose();
    phoneEditingController.dispose();
    super.onClose();
  }

  void addImages() async {
    var config = AssetPickerConfig(
      selectedAssets: state.images,
      maxAssets: 4,
      requestType: RequestType.image,
    );
    var result = await AssetPicker.pickAssets(
      Get.context!,
      pickerConfig: config,
    );
    if (result != null) {
      state.images = result;
      update();
    }
  }

  void removeImageAt(int index) {
    state.images.removeAt(index);
    update();
  }

  Future<void> submitButtonClicked() async {
    try {
      EasyLoading.show(status: '正在提交');
      List<String> files = [];
      await Future.forEach(state.images, (image) async {
        files.add(await filePathFromAssetEntity(image));
      });

      var result = await InteractDao.userFeedbackMul(
        feedbackText: feedbackEditingController.text.trim(),
        contacts: phoneEditingController.text.trim(),
        files: files,
      );
      if (result.code == 0) {
        if (result.data != null) {
          if (result.data!.state == true) {
            EasyLoading.showSuccess(
              '提交成功',
              duration: const Duration(seconds: 2),
            );
            Future.delayed(const Duration(seconds: 2), () {
              // 成功返回
              Get.back();
            });
          } else {
            EasyLoading.showError(result.message);
          }
        } else {
          EasyLoading.showError(result.message);
        }
      } else {
        EasyLoading.showError(result.message);
      }
    } catch (_) {
      EasyLoading.showError('提交失败');
    }
  }

  Future<String> filePathFromAssetEntity(AssetEntity entity) async {
    var path = '';
    final file = await entity.file;
    if (file != null) {
      path = file.path;
    }
    return path;
  }
}
